package com.jiawa.wordgz;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.nio.charset.StandardCharsets;
import java.net.URLEncoder;
import org.springframework.stereotype.Service;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import static com.jiawa.wordgz.DocxImg.sealInWord;
import static com.jiawa.wordgz.DocxTest.searchAndReplace;

@Service
public class DownService {

    public void handleAndDownloadDocument(String srcPath, String destPath, Map<String, String> replaceMap, HttpServletResponse response) throws IOException {
        try {
            // 调用你的方法处理文档
            searchAndReplace(srcPath, destPath, replaceMap);

            // 设置响应头，指示浏览器这是一个文件下载
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=\"modified_document.docx\"");

            // 读取临时文件并写入到response的输出流中
            FileInputStream fis = new FileInputStream(destPath);
            ServletOutputStream sos = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                sos.write(buffer, 0, bytesRead);
            }
            sos.flush();
            sos.close();
            fis.close();

            // 可选：删除临时文件
//             new File(destPath).delete();

        } catch (Exception e) {
            throw new IOException("Error processing the document", e);
        }
    };




        //firstParty第一个
        //partyToB第二个
       //注意这里tabText不能一行，因为第一个章已经在图片上，会报错
        public void handleAndDownloadImg(String firstParty,String partyToB,String srcPath, String destPath,  String firstSealFilePath, String secondFilePath,  Map<String, String> replaceMap, HttpServletResponse response) throws IOException {
            try {
                sealInWord(srcPath, destPath, firstParty, "甲      方", 100, 100, 140, -50, false);

                sealInWord(destPath,firstSealFilePath, partyToB, "或授权委托人", 100, 100, 350, -100, false);

                searchAndReplace(firstSealFilePath, secondFilePath, replaceMap);
                new File(destPath).delete();
                new File(firstSealFilePath).delete();
                // 可选：删除临时文件
                // 设置响应头，指示浏览器这是一个文件下载
                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//                response.setHeader("Content-Disposition", "attachment; filename=\"盖章协议.docx\"");
                LocalDateTime now = LocalDateTime.now(); // 获取当前日期时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss", Locale.getDefault()); // 设置日期时间格式
                String formattedDateTime = now.format(formatter); // 格式化日期时间
                String originalFileName = "盖章协议_" + formattedDateTime + ".docx";
                String encodedFileName = URLEncoder.encode(originalFileName, StandardCharsets.UTF_8.toString()).replace("+", "%20"); // 对文件名进行URL编码，并将'+'替换为'%20'
                response.setHeader("Content-Disposition",
                        String.format("attachment; filename=\"%s\"; filename*=utf-8''%s",
                                originalFileName,
                                encodedFileName)); // 使用原始文件名和URL编码后的文件名
                // 读取临时文件并写入到response的输出流中
                FileInputStream fis = new FileInputStream(secondFilePath);
                ServletOutputStream sos = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    sos.write(buffer, 0, bytesRead);
                }
                sos.flush();
                sos.close();
                fis.close();
             new File(secondFilePath).delete();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    public static boolean deleteFileWithRetry(String filePath, int retryCount, long sleepMillis) {
        File storeFile = new File(filePath);
        while (retryCount > 0) {
            if (storeFile.exists() && storeFile.isFile()) {
                boolean deleted = storeFile.delete();
                if (deleted) {
                    System.out.println("文件 " + filePath + " 已被删除.");
                    return true;
                } else {
                    System.out.println("尝试删除文件 " + filePath + " 但未能成功，剩余尝试次数：" + retryCount);
                    // 尝试通过运行finalizer来帮助释放资源
                    System.runFinalization();
                    retryCount--;
                    try {
                        Thread.sleep(sleepMillis); // 每次尝试之间等待指定时间
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return false; // 如果中断，提前结束并返回false
                    }
                }
            } else {
                System.out.println("文件 " + filePath + " 不存在或不是一个常规文件，无需删除.");
                return true; // 文件不存在或已删除，视为成功
            }
        }
        System.out.println("删除文件 " + filePath + " 失败，可能仍有其他进程在使用该文件.");
        return false; // 所有尝试均失败后返回false
    }

    }
